from datetime import datetime
from flask import Flask
from flask_marshmallow import Marshmallow
from marshmallow import Schema,fields

app = Flask(__name__)

ma = Marshmallow()
ma.init_app(app)

class User(object):
    def __init__(self, name, email):
        self.name = name
        self.email = email
        self.created_at = datetime.now()
        self.friends = []

class UserSchema(Schema):
    name = fields.String()
    email = fields.Email()
    created_at = fields.DateTime(format='%Y-%m-%d %H:%H:%S')

    # 自嵌套--->方式3：使用Pluck字段可以用单个值来替换嵌套对象的数据。
    friends = fields.Pluck("self", "name", many=True)

@app.route("/")
def index():
    # 自嵌套
    user0 = User(name="小明",email="123@qq.com")
    user1 = User(name="小红",email="123@qq.com")
    user2 = User(name="小白",email="123@qq.com")
    user3 = User(name="小黑",email="123@qq.com")
    user0.friends = [user1,user2,user3]
    us = UserSchema()
    user0 = us.dump(user0)
    print(user0)
    """运行结果：
    {
        'name': '小明', 
        'email': '123@qq.com', 
        'created_at': '2021-03-02 12:12:10', 
        'friends': [
            '小红', 
            '小白', 
            '小黑',
        ]
    }
    """
    return "hello"

if __name__ == '__main__':
    app.run(debug=True,host="0.0.0.0",port=5999)